package com.xjh.t.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjh.t.common.*;
import com.xjh.t.domain.*;
import com.xjh.t.service.*;
import com.xjh.t.vo.GroupAuditInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-03-13
 */
@RestController
@RequestMapping("/requestInfo")
public class RequestInfoController {

    @Autowired
    private IRequestInfoService requestInfoService;
    @Autowired
    private IAreaInfoService areaInfoService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IGroupInfoService groupInfoService;

    @Autowired
    private IDbInfoService dbInfoService;
    @Autowired
    private IGroupAttrInfoService groupAttrInfoService;
    @Autowired
    private IOperateLogService operateLogService;

    @Autowired
    private IExpressInfoService expressInfoService;

    @RequestMapping("/loadAllAuditComapny")
    public DataGridView loadAllAuditComapny(GroupAuditInfoVo groupAuditInfoVo)
    {
        IPage<RequestInfo> page = new Page<>(groupAuditInfoVo.getPage(),groupAuditInfoVo.getLimit());
        QueryWrapper<RequestInfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.like(StringUtils.isNotBlank(groupAuditInfoVo.getGpName()),"rt_info",groupAuditInfoVo.getGpName());
        queryWrapper.eq(groupAuditInfoVo.getRtResult() != null && groupAuditInfoVo.getRtResult() != 3,"rt_result",groupAuditInfoVo.getRtResult());

        queryWrapper.orderByDesc("rt_date");
        this.requestInfoService.page(page,queryWrapper);
        List<RequestInfo> list = page.getRecords();
        List<GroupAuditInfoVo> groupAuditInfoVoList = new ArrayList<>();

        List<UserInfo> userInfos = this.userInfoService.list();
        Map<Integer,String> userAccount = userInfos.stream().collect(Collectors.toMap(UserInfo::getUrId, UserInfo::getUrPhonenumber));

        User user =  (User) WebUtils.getSession().getAttribute("user");

        String areas = "";
        List<String> alldutyAreaId = new ArrayList<>();

        for(RequestInfo requestInfo:list)
        {
            GroupAuditInfoVo groupAuditInfoVo1 = new GroupAuditInfoVo();
            BeanUtils.copyProperties(requestInfo,groupAuditInfoVo1);

            groupAuditInfoVo1.parseCompanyInfo();

            boolean isunderDuty = false;
            if(alldutyAreaId.size() > 0)
            {
                Integer town = Integer.parseInt(groupAuditInfoVo1.getGpZone())/1000;
                if(alldutyAreaId.indexOf(town.toString()) >= 0)
                    isunderDuty = true;

                Integer city = Integer.parseInt(groupAuditInfoVo1.getGpZone())/100000;
                if(alldutyAreaId.indexOf(city.toString() + "00") >= 0)
                    isunderDuty = true;

                Integer province = Integer.parseInt(groupAuditInfoVo1.getGpZone())/10000000;
                if(alldutyAreaId.indexOf(province.toString() + "0000") >= 0)
                    isunderDuty = true;

            }
            else
                isunderDuty = true;

            if(isunderDuty) {
                if (userAccount.get(groupAuditInfoVo1.getUrId()) != null)
                    groupAuditInfoVo1.setCreateUserAccount(userAccount.get(groupAuditInfoVo1.getUrId()));
                else
                    groupAuditInfoVo1.setCreateUserAccount("");


                String addr = "";
                AreaInfo areaInfo = this.areaInfoService.getById(groupAuditInfoVo1.getGpZone());
                while (areaInfo != null && areaInfo.getAaLevel() != Constast.POLICY_TOP_LEVEL) {
                    addr = areaInfo.getAaAreaname() + " " + addr;
                    areaInfo = this.areaInfoService.getById(areaInfo.getAaParentid());
                }
                if(areaInfo != null)
                    addr = areaInfo.getAaAreaname() + " " + addr;
                else
                    System.out.println(groupAuditInfoVo1.getGpZone());

                groupAuditInfoVo1.setGpPolicyAddr(addr);

                groupAuditInfoVoList.add(groupAuditInfoVo1);
            }

        }

        return new DataGridView(groupAuditInfoVoList.size(),groupAuditInfoVoList);

    }

    @RequestMapping("/passRequest")
    public ResultObj passRequest(GroupAuditInfoVo groupAuditInfoVo) throws NoSuchFieldException, IllegalAccessException {


        RequestInfo requestInfo = this.requestInfoService.getById(groupAuditInfoVo.getRtId());
        if(requestInfo.getRtResult() != 0)
        {
            return ResultObj.REQUEST_HAS_PASS;
        }
        if(requestInfo != null && requestInfo.getRtResult() != groupAuditInfoVo.getRtResult())
        {
            User user =  (User) WebUtils.getSession().getAttribute("user");
            if(user == null)
                return  ResultObj.OFFLINE_ERROR;

            requestInfo.setRtResult(groupAuditInfoVo.getRtResult());
            requestInfo.setRtOptDate(new Date());
            requestInfo.setUrOptId(user.getId());
            this.requestInfoService.updateById(requestInfo);


            OperateLog operateLog = new OperateLog();
            operateLog.setOpId(user.getId());
            operateLog.setOpUsername(user.getName());
            operateLog.setOpType(Constast.OPERATE_TYPE.AUDIT.ordinal());
            StringBuilder builder = new StringBuilder();
            builder.append("公司审核,");
            builder.append("公司账号：" + groupAuditInfoVo.getCreateUserAccount() + ",");
            if(groupAuditInfoVo.getRtResult() == 1)
                builder.append("通过审核");
            else if(groupAuditInfoVo.getRtResult() == 2)
                builder.append("审核拒绝");

            operateLog.setOpMsg(builder.toString());
            operateLog.setOpData( groupAuditInfoVo.getRtResult().toString());
            operateLog.setOpTime(new Date());
            this.operateLogService.save(operateLog);

            if(groupAuditInfoVo.getRtResult() == 1)
            {
                QueryWrapper<DbInfo> dbInfoQueryWrapper = new QueryWrapper<>();
                dbInfoQueryWrapper.orderByAsc("db_gp_num");
                List<DbInfo> dbInfos = this.dbInfoService.list(dbInfoQueryWrapper);
                DbInfo dbInfo = dbInfos.get(0);

                dbInfo.setDbGpNum(dbInfo.getDbGpNum() + 1);
                this.dbInfoService.updateById(dbInfo);

                GroupInfo groupInfo = new GroupInfo();
                groupInfo.setGpName(groupAuditInfoVo.getGpName());
                groupInfo.setGpShortname(groupAuditInfoVo.getGpShortname());
                groupInfo.setGpBalance(0);
                groupInfo.setGpAddr(groupAuditInfoVo.getGpAddr());
                groupInfo.setGpLicense(groupAuditInfoVo.getGpLicense());
                groupInfo.setGpZone(groupAuditInfoVo.getGpZone());
                groupInfo.setDbId(dbInfo.getDbId());
                groupInfo.setGpStatus((long)(0));
                groupInfo.setUrId(groupAuditInfoVo.getUrId().longValue());
                groupInfo.setGpRegDate(new Date());
                groupInfo.setGpOrgcode(groupAuditInfoVo.getSocialCode());
                this.groupInfoService.save(groupInfo);

                DynamicDbTool.switchDb(IGroupAttrInfoService.class,dbInfo.getDbId());



                QueryWrapper<GroupInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("ur_id",groupAuditInfoVo.getUrId().longValue());
                List<GroupInfo> saveinfo = this.groupInfoService.list(queryWrapper);



                if(saveinfo.size() > 0)
                {
                    UserInfo userInfo = this.userInfoService.getById(saveinfo.get(0).getUrId());
                    if(userInfo != null)
                    {
                        userInfo.setGpId(saveinfo.get(0).getGpId().intValue());
                        this.userInfoService.updateById(userInfo);
                    }

                    GroupAttrInfo groupAttrInfo = new GroupAttrInfo();
                    groupAttrInfo.setGpId(saveinfo.get(0).getGpId().intValue());
                    groupAttrInfo.setDrMaxId(0);
                    groupAttrInfo.setEsDefaultId(0);
                    groupAttrInfo.setFileTotalSize((long)(0));

                    this.groupAttrInfoService.save(groupAttrInfo);

                    ExpressInfo expressInfo = new ExpressInfo();
                    expressInfo.setEsStatus(1);
                    expressInfo.setEsAddr(groupInfo.getGpAddr());
                    expressInfo.setEsCnee(groupInfo.getGpShortname());
                    expressInfo.setEsPhonenumber(userInfo.getUrPhonenumber());

                    expressInfo.setEsZone(groupInfo.getGpZone() + "|" + groupInfo.getGpZone().substring(0,6));
                    expressInfo.setUrId(groupInfo.getUrId().intValue());
                    expressInfo.setGpId(saveinfo.get(0).getGpId().intValue());

                    String addr = "";
                    AreaInfo areaInfo = this.areaInfoService.getById(groupInfo.getGpZone());
                    while (areaInfo != null && areaInfo.getAaLevel() != Constast.POLICY_TOP_LEVEL)
                    {
                        addr = areaInfo.getAaAreaname() + " " + addr;
                        areaInfo = this.areaInfoService.getById(areaInfo.getAaParentid());
                    }
                    if(areaInfo == null)
                    {
                        System.out.println(groupInfo.getGpId() + "," + groupInfo.getGpName());
                    }
                    else
                        addr = areaInfo.getAaAreaname() + " " + addr;

                    expressInfo.setEsZoneName(addr);
                    expressInfoService.save(expressInfo);


                }

            }
            return ResultObj.REQUEST_AUDIT_SUCESS;

        }
        else
            return ResultObj.REQUEST_HAS_PASS;
    }

}

